package cn.xiaolang.rest.remote;

import lombok.ToString;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.web.util.UriTemplate;

import java.io.Serializable;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

@ToString
public abstract class RestApiRequest implements Serializable {

    private String resourcePath;

    private HttpMethod httpMethod = HttpMethod.GET;

    private String endPointUri;

    public abstract String getApiBaseUrl();

    private HttpHeaders httpHeaders;

    public String getResourcePath() {
        return resourcePath;
    }

    public void setResourcePath(String resourcePath, Map<String, String> pathParamMap) {
        this.resourcePath = resourcePath;
        this.endPointUri = buildUrl(pathParamMap);
    }

    public HttpMethod getHttpMethod() {
        return httpMethod;
    }

    public void setHttpMethod(HttpMethod httpMethod) {
        this.httpMethod = httpMethod;
    }

    public String getEndPointUri() {
        return (endPointUri == null || endPointUri.isEmpty()) ? this.getApiBaseUrl() : endPointUri;
    }

    private String buildUrl(Map<String, String> parameterMap) {
        if (parameterMap == null) {
            parameterMap = new HashMap<>();
        }
        URI uriTemplate = new UriTemplate(this.getApiBaseUrl() + resourcePath).expand(parameterMap);
        RequestEntity<?> entity = RequestEntity.get(uriTemplate).build();
        return entity.getUrl().toASCIIString();
    }

    public HttpHeaders getHttpHeaders() {
        return httpHeaders;
    }

    public void setHttpHeaders(HttpHeaders httpHeaders) {
        this.httpHeaders = httpHeaders;
    }
}
